/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.employee.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.beanvalidator.BeanValidators;
import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.utils.DateUtils;
import com.chlitina.store.common.utils.excel.ExportExcel;
import com.chlitina.store.common.utils.excel.ImportExcel;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.service.CustomerEmployeeRelationshipService;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.employee.service.EmployeeService;
import com.chlitina.store.modules.employee.service.StoreBonusSettingCardService;
import com.chlitina.store.modules.employee.service.StoreBonusSettingCareService;
import com.chlitina.store.modules.employee.service.StoreBonusSettingProductService;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 店员Controller
 * @author lvbo
 * @version 2013-07-05
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/employee/employee")
public class EmployeeController extends BaseController {

	@Autowired
	private EmployeeService employeeService;
	
	@Autowired
	private CustomerEmployeeRelationshipService customerEmployeeRelationshipService;
	@Autowired
	private StoreBonusSettingCardService storeBonusSettingCardService;
	@Autowired
	private StoreBonusSettingCareService storeBonusSettingCareService;
	@Autowired
	private StoreBonusSettingProductService storeBonusSettingProductService;
	
	@ModelAttribute
	public Employee get(@RequestParam(required=false) Long id) {
		if (id != null){
			return employeeService.get(id);
		}else{
			return new Employee();
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "employeeData")
	public String employeeData(HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		return employeeService.getEmployees();
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(@RequestParam(required=false)String currentSelectId, Employee employee, HttpServletRequest request, HttpServletResponse response, Model model) {
		String status = request.getParameter("status");
		int statusInt = 0;
		try {
			statusInt = Integer.parseInt(status);
		} catch (Exception e) {
		}
        Page<Employee> page = employeeService.find(new Page<Employee>(request, response), employee, statusInt); 
        model.addAttribute("status", status);
        model.addAttribute("currentSelectId", currentSelectId);
        model.addAttribute("page", page);
		return "modules/employee/employeeList";
	}

	@RequestMapping(value = "bonusList")
	public String bonusList(@RequestParam(required=false)String currentSelectId, Employee employee, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<Employee> page = employeeService.find(new Page<Employee>(request, response), employee, Employee.STATUS_WORKING); 
        model.addAttribute("page", page);
        model.addAttribute("currentSelectId", currentSelectId);
		return "modules/employee/employeeBonusList";
	}
	
	@ResponseBody
	@RequestMapping(value = "copyBonus")
	public String copyBonus(HttpServletRequest request, HttpServletResponse response, Model model) {
		String employeeId = request.getParameter("employeeId");
		String type = request.getParameter("type");
		String from = request.getParameter("from");
		String ifModify = request.getParameter("ifModify");
		if(type.equals("0")){
			storeBonusSettingCardService.copy(employeeService.get(Long.parseLong(employeeId)), Integer.parseInt(ifModify));
			storeBonusSettingCareService.copy(employeeService.get(Long.parseLong(employeeId)), Integer.parseInt(ifModify));
			storeBonusSettingProductService.copy(employeeService.get(Long.parseLong(employeeId)), Integer.parseInt(ifModify));
		} else {
			Employee formEmployee = employeeService.get(Long.parseLong(from));
			storeBonusSettingCardService.copy(employeeService.get(Long.parseLong(employeeId)), Integer.parseInt(ifModify), formEmployee);
			storeBonusSettingCareService.copy(employeeService.get(Long.parseLong(employeeId)), Integer.parseInt(ifModify), formEmployee);
			storeBonusSettingProductService.copy(employeeService.get(Long.parseLong(employeeId)), Integer.parseInt(ifModify), formEmployee);
		}
		return "true";
	}
	
	@RequestMapping(value = "form")
	public String form(Employee employee, ModelMap model) {
		Date birthday = employee.getBirthday();
		if (birthday != null) {
			java.sql.Date sqlDate = new java.sql.Date(birthday.getTime());
			employee.setBirthday(sqlDate);
		}
		model.addAttribute("employee", employee);
		return "modules/employee/employeeForm";
	}
	
	@RequestMapping(value = "detail")
	public String detail(Employee employee, ModelMap model) {
		Date birthday = employee.getBirthday();
		if (birthday != null) {
			java.sql.Date sqlDate = new java.sql.Date(birthday.getTime());
			employee.setBirthday(sqlDate);
		}
		model.addAttribute("employee", employee);
		return "modules/employee/employeeDetail";
	}

	@RequestMapping(value = "save")
	public String save(Employee employee, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, employee)){
			return form(employee, (ModelMap)model);
		}
		Long id = employee.getId();
		employeeService.save(employee);
		if (id == null) {
			addMessage(redirectAttributes, "添加店员"+ employee.getName() + "成功");
		} else {
			addMessage(redirectAttributes, "修改店员"+ employee.getName() + "成功");
		}
		return "redirect:"+Global.ADMIN_PATH+"/employee/employee/detail?id="+ employee.getId();
	}
	
	@RequestMapping(value = "status")
	public String status(Long id, RedirectAttributes redirectAttributes) {
		try {
			Employee employee = employeeService.get(id);
			employeeService.changeStatus(employee);
			addMessage(redirectAttributes, "店员状态更改成功！");
		} catch (Exception e) {
			addMessage(redirectAttributes, "无法更改此店员的状态");
		}
		return "redirect:"+Global.ADMIN_PATH+"/employee/employee/";
	}
	
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		try {
			employeeService.delete(id);
			addMessage(redirectAttributes, "删除店员成功");
		} catch (Exception e) {
			addMessage(redirectAttributes, "无法删除此店员");
		}
		return "redirect:"+Global.ADMIN_PATH+"/employee/employee/";
	}

	@ResponseBody
	@RequestMapping(value = "export")
	public String exportFile(String name,String status, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes) {
		int statusInt = 0;
		try {
			statusInt = Integer.parseInt(status);
		} catch (Exception e) {
		}
		String fileName = "";
		String errorMsg = "";
		ExportExcel write = null;
		try {
			List<Employee> employees = employeeService.export(name, statusInt);
			if (employees == null || employees.size() == 0) {
				errorMsg = "不存在导出数据";
			} else {
				fileName = "employee" + DateUtils.getDate("yyyyMMddHHmmss") + ".xls";
				write = new ExportExcel("员工数据", Employee.class, 1).setDataList(employees);
				write.write(response, fileName);
				return null;
			}
		} catch (Exception e) {
			errorMsg = "导出员工数据失败！失败信息：" + e.getMessage();
			addMessage(redirectAttributes, errorMsg);

		} finally{
			if (write != null) {
				write.dispose();
			}
		}
		System.out.println(fileName);
		return "redirect:" + Global.ADMIN_PATH + "/employee/employee/";
	}

	@ResponseBody
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file,
			RedirectAttributes redirectAttributes) {
		int successNum = 0;
		int failureNum = 0;
		StringBuilder failureMsg = new StringBuilder();
		try {
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Employee> list = ei.getDataList(Employee.class);
			for (Employee employee : list) {
				if (employee.getName() == null) {
					failureNum++;
					continue;
				}
				try {
					if ("true".equals(isExist(employee.getSfzh()))) {
						employee.setGender(0);
						employee.setStore(StoreUtils.getStore());
						employee.setSalary(0);
						employee.setStatus(0);
						//店员角色默认为美容师
						employee.setStoreRole(StoreUtils.getStoreRole(3L));
						BeanValidators.validateWithException(validator, employee);
						employeeService.save(employee);
						successNum++;
					} else {
						failureMsg.append("员工 " + employee.getName()
								+ " 已存在; ");
						failureNum++;
					}
				} catch (ConstraintViolationException ex) {
					failureMsg.append("员工 " + employee.getName()
							+ " ");
					List<String> messageList = BeanValidators
							.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList) {
						failureMsg.append(message + "; ");
						failureNum++;
					}
				} catch (Exception ex) {
					failureMsg.append("员工 " + employee.getName()
							+ " 导入失败;");
				}
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		Map<String, String> map = Maps.newHashMap();
		map.put("successNum", successNum + "");
		map.put("failureNum", failureNum + "");
		map.put("errorMsg", failureMsg.toString());
		return JsonMapper.getInstance().toJson(map);
	}

	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		ExportExcel write = null;
		try {
			String fileName = "店面员工数据导入模板.xls";
			List<Employee> list = Lists.newArrayList();
			Employee e = new Employee();
			e.setName("姓名");
			e.setBirthday(new Date());
			e.setSfzh("身份证号");
			e.setMobile("手机号码");
			list.add(e);
			write = new ExportExcel("员工数据", Employee.class, 2).setDataList(list);
			write.write(response, fileName);
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		} finally {
			if (write != null) {
				write.dispose();
			}
		}
		return "redirect:" + Global.ADMIN_PATH + "/employee/employee/";
	}

	@ResponseBody
	@RequestMapping(value = "delRealtionship")
	public String delRealtionship(@RequestParam(required=true) Long employeeId, HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		int sum = 0;
		try {
			sum = customerEmployeeRelationshipService.delete(null, employeeId);
		} catch (Exception e) {
			sum = 0;
		}
		Map<String, Integer> result = Maps.newHashMap();
		result.put("sum", sum);
		return JsonMapper.getInstance().toJson(result);
	}
	@ResponseBody
	@RequestMapping(value = "allCustomers")
	public String allCustomers(HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		Map<Long, String> storeCustomerList = StoreUtils.getStoreCustomerList();
		return JsonMapper.getInstance().toJson(storeCustomerList);
	}
	
	@ResponseBody
	@RequestMapping(value = "isExist")
	public String isExist(String oldSFZH) {
		List<Employee> list = employeeService.isExist(oldSFZH);
		if (list == null || list.size() == 0) {
			return "true";
		}
		return "false";
	}

}
